<template>
  <div class="editInfo">
    <navBar
      :title="titleObj[type]"
      rightText="保存"
      :path="path"
      @clickRight="save"
    ></navBar>
    <div class="content">
      <van-field
        v-if="type !== 'avatar'"
        class="avatar"
        v-model="fieldValue"
      ></van-field>
      <van-uploader
        class=""
        v-else
        v-model="fileList"
        show-upload
        :max-count="1"
        @before-read="beforeRead"
        :after-read="afterRead"
      ></van-uploader>
    </div>
  </div>
</template>

<script>
import { auEdit, Upload } from "@/api/my.js";
import { mapState } from "vuex";
export default {
  data() {
    return {
      fieldValue: "",
      type: this.$route.query.type,
      path: "/home/myInfo",
      fileList: [],
      titleObj: {
        nickname: "修改昵称",
        intro: "修改简介",
        position: "修改岗位",
        avatar: "修改头像",
      },
    };
  },
  computed: {
    ...mapState(["userInfo"]),
  },
  created() {
    this.fieldValue = this.userInfo[this.type];
    if (this.type === "avatar") {
      if (this.userInfo.avatar) {
        this.fileList = [
          { url: process.env.VUE_APP_URL + this.userInfo.avatar },
        ];
      }
    }
    if (this.type === "position") {
      this.path = "/home/my";
    }
  },
  methods: {
    save() {
      auEdit({ [this.type]: this.fieldValue })
        .then(() => {
          this.$toast.success("修改成功");
          this.$store.dispatch("refreshUserInfo");
          this.$router.push(this.path);
        })
        .catch();
    },
    // 文件上传前
    beforeRead(flie) {
      const isPng = file.type === "img/png" || file.type === "img/png";
      const limit2M = file.size / 1024 / 1024 < 2;
      if (!isPng) {
        this.$toast.fail("请上传PNG、JPG格式图片");
      }
      if (!limit2M) {
        this.$toast.fail("请上传2M内的文件");
      }
      return isPng && limit2M;
    },
    // 文件上传后
    afterRead(file) {
      window.console.log(file);
      const _formData = new FormData();
      _formData.append("files", file.file);
      this.$toast.loading({
        duration: 0,
        message: "上传中",
      });
      Upload(_formData).then((res) => {
        window.console.log(res);
        this.$toast.clear();
        this.fieldValue = res.data.data[0].id;
      });
    },
  },
};
</script>

<style lang="less" scoped>
.editInfo {
  .content {
    padding: 20px @p15;
    text-align: center;
    .avatar {
      background: #f7f4f5;
      border-radius: 8px;
    }
  }
}
</style>